package com.gopay.scheduler.service.cbrmb.impl;

import com.gopay.common.cps.dao.cbrmb.CbRmbTranAssistDtlDao;
import com.gopay.common.domain.cbrmb.CbRmbTranAssistDtl;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.cbrmb.CbRmbCcbBankRemoteService;
import com.gopay.scheduler.service.cbrmb.CbRmbCCBCheckOrderService;
import com.gopay.scheduler.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author b.zou
 * @description
 * @class CbRmbCCBCheckOrderServiceImpl
 * @date 2018.2.8
 */
@Service(value = "cbRmbCCBCheckOrderService")
public class CbRmbCCBCheckOrderServiceImpl implements CbRmbCCBCheckOrderService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource(name = "cbRmbTranAssistDtlDao")
    private CbRmbTranAssistDtlDao cbRmbTranAssistDtlDao;

    @Resource(name = "cbRmbCcbBankRemoteServiceClient")
    private CbRmbCcbBankRemoteService cbRmbCcbBankRemoteServiceClient;

    @Override
    public List<CbRmbTranAssistDtl> getOrderList() {
        Calendar time = Calendar.getInstance();
        String timeBeginString = DateUtils.format(time.getTime(), "yyyyMMdd") + "000000";
        String timeEndString = DateUtils.format(time.getTime(), "yyyyMMdd") + "235959";
        Map<String,Object> params = new HashMap<>();
        params.put("timeBeginString", timeBeginString);
        params.put("timeEndString", timeEndString);
        String hql = " from CbRmbTranAssistDtl t where t.state in('02','04','05') and t.checkNum<8 " +
                "and t.bpFinishTime>=to_timestamp(:timeBeginString, 'yyyymmddHH24miss')" +
                "and t.bpFinishTime<=to_timestamp(:timeEndString, 'yyyymmddHH24miss')" +
                " order by t.cbRmbDtlSq desc ";
        List<CbRmbTranAssistDtl> list = cbRmbTranAssistDtlDao.findByHql(hql,params);
        return list;
    }

    @Override
    public void ccbCheckOrder(CbRmbTranAssistDtl dtl) throws GopayException {
        int checkNum = dtl.getCheckNum()+1;
        dtl.setCheckNum(checkNum);
        cbRmbTranAssistDtlDao.update(dtl);
        String result = cbRmbCcbBankRemoteServiceClient.findCbRmbCcbResultByGopayOrderId(dtl.getGopayOrderId());
        if(null==result || !"0000".equals(result)){
            logger.info("跨境出款定时任务对账失败，订单号：{}",dtl.getGopayOrderId());
        }else{
            logger.info("跨境出款定时任务对账成功，订单号：{}",dtl.getGopayOrderId());
        }
    }
}
